/***************************************************************************
 *   Copyright (C) 2010 by Oleg Goncharov  *
 *   $EMAIL$                           *                          
 *                                                                         *
 *   This file is part of ChessVision.                                     *
 *                                                                         *
 *   ChessVision is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "cintegraldetector.h"

namespace Chess {

double CIntegralDetector::Integral(IplImage * grey, const SBoardPosition& bp, int r) {
	CvScalar scal;
	
	SBoardCells cells(bp.x - r, bp.y - r, bp.teta, bp.h);
	cv::Point2f sp = cells.Start(), p;
	int twor = 2*r;
	double integ = 0;
	
	for(int i = 0; i < 8; i++) {
		p = sp;
		for(int j = 0; j < 8; j++) {
			cvSetImageROI(grey, cvRect((int) p.x, (int) p.y, twor, twor));
			scal = cvAvg(grey);
			if ((i + j) & 1) integ += scal.val[0] - 128.0;
			else integ -= scal.val[0] - 128.0;
			cells.StepY(p);
		}
		cells.StepX(sp);
	}
	cvResetImageROI(grey);
	
	return integ;
}

}
